package com.example.serialportdemo;

import java.util.HashMap;
import java.util.Map;

import android_serialport_api.SerialPort;

public class SerialPortToolManager {

    private static final String TAG = "SerialPortToolManager";
    private Map<String, SerialPortTool> pool;

    private static SerialPortToolManager instance;

    public SerialPortToolManager() {
        pool = new HashMap<>();
    }

    public static SerialPortToolManager getInstance() {
        if (instance == null) {
            synchronized (SerialPortToolManager.class) {
                if (instance == null) {
                    instance = new SerialPortToolManager();
                }
            }
        }
        return instance;
    }

    /**
     * 打开某个串口
     * 一个串口号 对应一个串口工具类
     *
     * @param serialNum
     */
    public void openSerialPort(String serialNum, SerialPortTool.OnSerialPortDataReceiveListener listener) {
        if (getSerialPortTool(serialNum) != null) {
            LogUtil.d(TAG, "openSerialPort() returned:[" + serialNum + "]该串口已经开启...");
            return;
        } else {
            LogUtil.d(TAG, "openSerialPort() returned: " + "尝试打开串口" + serialNum);
        }
        SerialPortTool serialPortTool = new SerialPortTool(serialNum);
        SerialPort serialPort = serialPortTool.openSerialPort();
        if (serialPort != null) {
            serialPortTool.setOnSerialPortDataReceiveListener(listener);
            pool.put(serialNum, serialPortTool);
        } else {
            LogUtil.d(TAG, "openSerialPort() returned: [" + serialNum + "]串口开启失败");
        }
    }


    public SerialPortTool getSerialPortTool(String serialNum) {
        return pool.get(serialNum);
    }

    /**
     * 向某个串口发命令
     *
     * @param serialNum 串口号
     * @param hexStr    发送指令
     */
    public void sendSerialPortCMD_DATA(String serialNum, String hexStr) {
        SerialPortTool serialPortTool = getSerialPortTool(serialNum);
        serialPortTool.sendSerialPort(hexStr);
    }

    /**
     * 关闭某个串口
     *
     * @param serialNum
     */
    public void closeSerialPort(String serialNum) {
        SerialPortTool serialPortTool = getSerialPortTool(serialNum);
        serialPortTool.closeSerialPort();
    }

    public void closeAll() {
        for (String key : pool.keySet()) {
            pool.get(key).closeSerialPort();
        }
        pool = new HashMap<>();
    }
}

